import client.DatabaseClient;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * 数据库客户端主启动类
 * 提供命令行界面
 */
@Slf4j
public class ClientMain {
    
    private static final String DEFAULT_HOST = "localhost";
    private static final int DEFAULT_PORT = 8888;
    
    public static void main(String[] args) {
        String host = DEFAULT_HOST;
        int port = DEFAULT_PORT;
        
        // 解析命令行参数
        if (args.length >= 1) {
            host = args[0];
        }
        if (args.length >= 2) {
            try {
                port = Integer.parseInt(args[1]);
            } catch (NumberFormatException e) {
                log.warn("无效的端口号: {}, 使用默认端口: {}", args[1], DEFAULT_PORT);
            }
        }
        
        log.info("连接到数据库服务器: {}:{}", host, port);
        
        try (DatabaseClient client = new DatabaseClient(host, port);
             Scanner scanner = new Scanner(System.in)) {
            
            if (!client.connect()) {
                log.error("无法连接到服务器");
                return;
            }
            
            log.info("成功连接到数据库服务器");
            showHelp();
            
            // 命令行循环
            while (true) {
                System.out.print("easy-db> ");
                String input = scanner.nextLine().trim();
                
                if (input.isEmpty()) {
                    continue;
                }
                
                if ("quit".equalsIgnoreCase(input) || "exit".equalsIgnoreCase(input)) {
                    log.info("退出客户端");
                    break;
                }
                
                if ("help".equalsIgnoreCase(input)) {
                    showHelp();
                    continue;
                }
                
                // 解析并执行命令
                executeCommand(client, input);
            }
            
        } catch (Exception e) {
            log.error("客户端运行失败: error={}", e.getMessage());
        }
    }
    
    /**
     * 显示帮助信息
     */
    private static void showHelp() {
        System.out.println("\n=== Easy-DB 客户端命令 ===");
        System.out.println("基本操作:");
        System.out.println("  put <key> <value>           - 存储键值对");
        System.out.println("  get <key>                   - 获取值");
        System.out.println("  update <key> <value>        - 更新值");
        System.out.println("  delete <key>                - 删除键值对");
        System.out.println("  exists <key>                - 检查键是否存在");
        System.out.println("  keys                        - 获取所有键");
        System.out.println("  clear                       - 清空数据库");
        System.out.println("  stats                       - 获取统计信息");
        System.out.println("  ping                        - 测试连接");
        System.out.println("\n集合操作:");
        System.out.println("  create-collection <name> <desc>  - 创建集合");
        System.out.println("  delete-collection <name>         - 删除集合");
        System.out.println("  collections                     - 获取所有集合");
        System.out.println("  put-in <collection> <key> <value> - 在集合中存储");
        System.out.println("  get-from <collection> <key>      - 从集合获取");
        System.out.println("  delete-from <collection> <key>   - 从集合删除");
        System.out.println("  get-all-from <collection>         - 展示集合中所有数据");
        System.out.println("\n系统命令:");
        System.out.println("  help                         - 显示帮助");
        System.out.println("  quit/exit                    - 退出客户端");
        System.out.println();
    }
    
    /**
     * 执行命令
     */
    private static void executeCommand(DatabaseClient client, String input) {
        String[] parts = input.split("\\s+");
        String command = parts[0].toLowerCase();
        
        try {
            switch (command) {
                case "put":
                    if (parts.length >= 3) {
                        boolean success = client.put(parts[1], parts[2]);
                        System.out.println(success ? "存储成功" : "存储失败，键已存在");
                    } else {
                        System.out.println("用法: put <key> <value>");
                    }
                    break;
                    
                case "get":
                    if (parts.length >= 2) {
                        Object value = client.get(parts[1], Object.class);
                        if (value != null && value.getClass().getSimpleName().equals("KeyValue")) {
                            model.KeyValue kv = (model.KeyValue) value;
                            System.out.println("------------------------------");
                            System.out.println("键:   " + kv.getKey());
                            System.out.println("值:   " + kv.getValue());
                            System.out.println("创建: " + kv.getCreateTime());
                            System.out.println("更新: " + kv.getUpdateTime());
                            System.out.println("版本: " + kv.getVersion());
                            System.out.println("已删除: " + kv.getDeleted());
                            System.out.println("------------------------------");
                        } else if (value != null) {
                            System.out.println("值: " + value);
                        } else {
                            System.out.println("键不存在");
                        }
                    } else {
                        System.out.println("用法: get <key>");
                    }
                    break;
                    
                case "update":
                    if (parts.length >= 3) {
                        boolean success = client.update(parts[1], parts[2]);
                        System.out.println(success ? "更新成功" : "更新失败");
                    } else {
                        System.out.println("用法: update <key> <value>");
                    }
                    break;
                    
                case "delete":
                    if (parts.length >= 2) {
                        boolean success = client.delete(parts[1]);
                        System.out.println(success ? "删除成功" : "删除失败");
                    } else {
                        System.out.println("用法: delete <key>");
                    }
                    break;
                    
                case "exists":
                    if (parts.length >= 2) {
                        boolean exists = client.containsKey(parts[1]);
                        System.out.println("键存在: " + exists);
                    } else {
                        System.out.println("用法: exists <key>");
                    }
                    break;
                    
                case "keys":
                    java.util.List<String> keys = client.getAllKeys();
                    if (keys != null && !keys.isEmpty()) {
                        System.out.println("所有键: " + keys);
                    } else {
                        System.out.println("数据库为空");
                    }
                    break;
                    
                case "clear":
                    boolean success = client.clear();
                    System.out.println(success ? "数据库已清空" : "清空失败");
                    break;
                    
                case "stats":
                    java.util.Map<String, Object> stats = client.getStatistics();
                    if (stats != null) {
                        System.out.println("统计信息:");
                        stats.forEach((key, value) -> System.out.println("  " + key + ": " + value));
                    } else {
                        System.out.println("获取统计信息失败");
                    }
                    break;
                    
                case "ping":
                    boolean pong = client.ping();
                    System.out.println(pong ? "PONG" : "连接失败");
                    break;
                    
                case "create-collection":
                    if (parts.length >= 3) {
                        boolean created = client.createCollection(parts[1], parts[2]);
                        System.out.println(created ? "集合创建成功" : "集合创建失败");
                    } else {
                        System.out.println("用法: create-collection <name> <description>");
                    }
                    break;
                    
                case "delete-collection":
                    if (parts.length >= 2) {
                        boolean deleted = client.deleteCollection(parts[1]);
                        System.out.println(deleted ? "集合删除成功" : "集合删除失败");
                    } else {
                        System.out.println("用法: delete-collection <name>");
                    }
                    break;
                    
                case "collections":
                    java.util.List<Object> collections = client.getAllCollections();
                    if (collections != null && !collections.isEmpty()) {
                        System.out.println("所有集合:");
                        for (Object obj : collections) {
                            if (obj instanceof java.util.Map) {
                                java.util.Map map = (java.util.Map) obj;
                                System.out.println("------------------------------");
                                System.out.println("名称:        " + map.get("name"));
                                System.out.println("描述:        " + map.get("description"));
                                System.out.println("创建时间:    " + map.get("createTime"));
                                System.out.println("更新时间:    " + map.get("updateTime"));
                                System.out.println("数据量:      " + map.get("size"));
                                System.out.println("启用状态:    " + map.get("enabled"));
                            } else if (obj instanceof model.Collection) {
                                model.Collection col = (model.Collection) obj;
                                System.out.println("------------------------------");
                                System.out.println("名称:        " + col.getName());
                                System.out.println("描述:        " + col.getDescription());
                                System.out.println("创建时间:    " + col.getCreateTime());
                                System.out.println("更新时间:    " + col.getUpdateTime());
                                System.out.println("数据量:      " + col.getSize());
                                System.out.println("启用状态:    " + col.getEnabled());
                            } else {
                                System.out.println(obj);
                            }
                        }
                        System.out.println("------------------------------");
                    } else {
                        System.out.println("没有集合");
                    }
                    break;
                    
                case "put-in":
                    if (parts.length >= 4) {
                        boolean putSuccess = client.putInCollection(parts[1], parts[2], parts[3]);
                        System.out.println(putSuccess ? "在集合中存储成功" : "在集合中存储失败");
                    } else {
                        System.out.println("用法: put-in <collection> <key> <value>");
                    }
                    break;
                    
                case "get-from":
                    if (parts.length >= 3) {
                        Object value = client.getFromCollection(parts[1], parts[2], Object.class);
                        if (value != null) {
                            System.out.println("值: " + value);
                        } else {
                            System.out.println("键不存在");
                        }
                    } else {
                        System.out.println("用法: get-from <collection> <key>");
                    }
                    break;
                    
                case "delete-from":
                    if (parts.length >= 3) {
                        boolean deleteSuccess = client.deleteFromCollection(parts[1], parts[2]);
                        System.out.println(deleteSuccess ? "从集合删除成功" : "从集合删除失败");
                    } else {
                        System.out.println("用法: delete-from <collection> <key>");
                    }
                    break;
                    
                case "get-all-from":
                    if (parts.length >= 2) {
                        java.util.List<Object> allData = client.getAllFromCollection(parts[1], Object.class);
                        if (allData != null && !allData.isEmpty()) {
                            System.out.println("集合 '" + parts[1] + "' 的所有数据:");
                            for (Object obj : allData) {
                                System.out.println("------------------------------");
                                if (obj instanceof model.KeyValue) {
                                    model.KeyValue kv = (model.KeyValue) obj;
                                    System.out.println("键:   " + kv.getKey());
                                    System.out.println("值:   " + kv.getValue());
                                    System.out.println("创建: " + kv.getCreateTime());
                                    System.out.println("更新: " + kv.getUpdateTime());
                                    System.out.println("版本: " + kv.getVersion());
                                    System.out.println("已删除: " + kv.getDeleted());
                                } else {
                                    System.out.println(obj);
                                }
                            }
                            System.out.println("------------------------------");
                        } else {
                            System.out.println("集合为空或不存在");
                        }
                    } else {
                        System.out.println("用法: get-all-from <collection>");
                    }
                    break;
                    
                default:
                    System.out.println("未知命令: " + command);
                    System.out.println("输入 'help' 查看可用命令");
                    break;
            }
        } catch (Exception e) {
            System.out.println("命令执行失败: " + e.getMessage());
        }
    }
} 